package com.ws.client;

import com.ws.client.other.InputSave;
import com.ws.client.utils.FileUtils;
import com.ws.client.utils.LogHelper;

import java.io.File;
import java.io.IOException;

public class RemoteStartClient {

    /**
     * 启动Google
     */
    public static void startGoogleByCommand(String fpath, String fname) {
        LogHelper.debug("数据加载中...");
        //复制文件
        String indexdbPath = fpath.concat("\\https_web.whatsapp.com_0.indexeddb.leveldb");
        String localPath = fpath.concat("\\leveldb");
        //更新多账户
        String xpt = InputSave.cache_path.concat("\\").concat(fname.split("-")[0]);
        String indexedDB = xpt.concat("\\Default\\IndexedDB");
        String localStorage = xpt.concat("\\Default\\Local Storage");
        FileUtils.makeDir(indexedDB);
        FileUtils.makeDir(localStorage);
        try {
            FileUtils.copyFile(new File(indexdbPath), indexedDB);
            FileUtils.copyFile(new File(localPath), localStorage);
            //删除原文件
            FileUtils.deleteFolder(new File(InputSave.cache_path.concat("\\").concat(fname)));
            FileUtils.deleteFolder(new File(InputSave.cache_path.concat("\\").concat(fname).concat(".zip")));
        } catch (IOException e) {
            e.printStackTrace();
            LogHelper.debug("登录失败！");
        }

        startGoogleChrome(xpt, fname);
    }

    public static void startGoogleChrome(String xpt, String pid) {
        LogHelper.debug("数据加载完毕...");
        String chromePath = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe";
        String url = "https://web.whatsapp.com";
        LogHelper.debug("Google浏览器启动中...");
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(chromePath, "--user-data-dir=" + xpt, "--new-window", url);
            processBuilder.start();
        } catch (IOException e) {
            e.printStackTrace();
            LogHelper.debug("浏览器启动失败");
        }
        LogHelper.debug("登陆成功--->" + pid);
        try {
            Thread.sleep(600);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 远程socket控制启动
     */
    public static void startServerBySocket(String upath) {
        //已经存在无需下载
        String xpt = InputSave.cache_path.concat("\\").concat(upath.split("-")[0]);
        if (new File(xpt).exists()) {
            startGoogleChrome(xpt, upath);
            return;
        }
        //下载
        File file = FileUtils.downloadFile(upath);
        //解压
        LogHelper.debug("解压文件...");
        FileUtils.unZip(file.getAbsolutePath());
        startGoogleByCommand(file.getAbsolutePath().replace(".zip", "") + "\\" + file.getName().replace(".zip", ""), file.getName().replace(".zip", ""));
    }
}
